/*
Author : Nguyen Van Ty
Email  : ngvanty03@gmail.com
Date   : 3/4/2011 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Utility;
using BusinessObject;
using System.Xml;

namespace DataAccessLayer
{
    /// <summary>
    /// Define PhieuChuyenKhoDao class. This class inherit from  PhieuChuyenKhoDaoBase class.
    /// If you want add new function, you must define here.
    /// </summary>
    public class PhieuChuyenKhoDao : PhieuChuyenKhoDaoBase
    {
        private static ILog logger = null;
        #region Constructor
        /// <summary>
        /// Define Constructor.
        /// </summary>
        public PhieuChuyenKhoDao() { }
        static PhieuChuyenKhoDao()
        {
            // Init logger.
            logger = LoggingUtility.GetLogger(typeof(PhieuChuyenKhoDao).FullName);
        }
        public static Int64 Insert(PhieuChuyenKho obj, List<ChiTietPhieuChuyenKho> lstChiTiet)
        {
            String methodName = "InsertPhieuChuyenKho";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            ManagerDao.BeginTransaction();
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertPhieuChuyenKho");
            
            //Add value "ChungXe"  paramater.
            ManagerDao.AddInParameter(cmd, "ChungXe", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.ChungXe));
            //Add value "NguoiNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiNhap", DbType.String, obj.NguoiNhap);
            //Add value "MaKhoChuyen"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKhoChuyen", DbType.Int32, obj.MaKhoChuyen);
            ManagerDao.AddInParameter(cmd, "MaKhoDen", DbType.Int32, obj.MaKhoDen);
            //Add value "NgayNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayNhap", DbType.DateTime, obj.NgayNhap);
            ////////////////////////
            ManagerDao.AddInParameter(cmd, "SysCreatedBy", DbType.String, obj.SysCreatedBy);
            ManagerDao.AddInParameter(cmd, "SysCreatedDate", DbType.DateTime, obj.SysCreatedDate);
            ManagerDao.AddInParameter(cmd, "SysUpdatedBy", DbType.String, obj.SysUpdatedBy);
            ManagerDao.AddInParameter(cmd, "SysUpdatedDate", DbType.DateTime, obj.SysUpdatedDate);
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int64, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                Int64 id = Int64.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id > 0)//Successfull.
                {
                    if (lstChiTiet != null && lstChiTiet.Count > 0)
                    {
                        int TotalSoLuongTon = 0;
                        foreach (ChiTietPhieuChuyenKho objDetail in lstChiTiet)
                        {
                            //get TongSoLuongTon cua mat hang nay
                            TotalSoLuongTon = MatHangDao.GetSoLuongTonByDonViTinh(objDetail.MaMatHang, obj.MaKhoChuyen, objDetail.MaDonViTinh);
                            if (TotalSoLuongTon > 0)
                            {
                                if (objDetail.SoLuongChuyen > TotalSoLuongTon)
                                    objDetail.SoLuongChuyen = TotalSoLuongTon;
                                //insert table chi tiet phieu chuyen
                                objDetail.MaPhieuChuyenKho = id;
                                if (!ChiTietPhieuChuyenKhoDao.Insert(objDetail))
                                {
                                    ManagerDao.Rollback();
                                    return 0;
                                }
                                //tru bot mat hang ben kho A
                                MatHangTonKho objMatHangTonKhoA = new MatHangTonKho();
                                objMatHangTonKhoA.MaDonViTinh = objDetail.MaDonViTinh;
                                objMatHangTonKhoA.MaKho = obj.MaKhoChuyen;
                                objMatHangTonKhoA.MaMatHang = objDetail.MaMatHang;
                                objMatHangTonKhoA.SoLuongTon = objDetail.SoLuongChuyen;
                                if (!MatHangTonKhoDao.RemoveMatHangTonKho(objMatHangTonKhoA))
                                {
                                    ManagerDao.Rollback();
                                    return 0;
                                }
                                //chuyen wa kho B
                                MatHangTonKho objMatHangTonKhoB = new MatHangTonKho();
                                objMatHangTonKhoB.MaDonViTinh = objDetail.MaDonViTinh;
                                objMatHangTonKhoB.MaKho = obj.MaKhoDen;
                                objMatHangTonKhoB.MaMatHang = objDetail.MaMatHang;
                                objMatHangTonKhoB.SoLuongTon = objDetail.SoLuongChuyen;
                                if (!MatHangTonKhoDao.Insert(objMatHangTonKhoB))
                                {
                                    ManagerDao.Rollback();
                                    return 0;
                                }
                            }
                        }

                    }
                    ManagerDao.Commit();
                    return id;
                }
                else
                {
                    ManagerDao.Rollback();
                    return 0;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            ManagerDao.Rollback();
            return 0;
        }
        public static bool Update(PhieuChuyenKho obj, List<ChiTietPhieuChuyenKho> lstChiTiet)
        {
            String methodName = "UpdatePhieuChuyenKho";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            ManagerDao.BeginTransaction();
            PhieuChuyenKho objOld = PhieuChuyenKhoDao.Get(obj.MaPhieuChuyenKho);
            if (objOld == null)
            {
                ManagerDao.Rollback();
                return false;
            }           
            //get all data
            List<ChiTietPhieuChuyenKhoResult> lstOldData = ChiTietPhieuChuyenKhoDao.GetByMaPhieuChuyenKho(obj.MaPhieuChuyenKho);
            if (lstOldData == null)
            {
                ManagerDao.Rollback();
                return false;
            }
            if (lstOldData.Count < 1)
            {
                ManagerDao.Rollback();
                return false;
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdatePhieuChuyenKho");
            //Add value "MaPhieuChuyenKho"  paramater.
            ManagerDao.AddInParameter(cmd, "MaPhieuChuyenKho", DbType.Int32, obj.MaPhieuChuyenKho);
            //Add value "ChungXe"  paramater.
            ManagerDao.AddInParameter(cmd, "ChungXe", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.ChungXe));
            //Add value "NguoiNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiNhap", DbType.String, obj.NguoiNhap);
            //Add value "MaKhoChuyen"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKhoChuyen", DbType.Int32, obj.MaKhoChuyen);
            ManagerDao.AddInParameter(cmd, "MaKhoDen", DbType.Int32, obj.MaKhoDen);
            //Add value "NgayNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayNhap", DbType.DateTime, obj.NgayNhap);

            //ManagerDao.AddInParameter(cmd, "SysCreatedBy", DbType.String, obj.SysCreatedBy);
            //ManagerDao.AddInParameter(cmd, "SysCreatedDate", DbType.DateTime, obj.SysCreatedDate);
            ManagerDao.AddInParameter(cmd, "SysUpdatedBy", DbType.String, obj.SysUpdatedBy);
            ManagerDao.AddInParameter(cmd, "SysUpdatedDate", DbType.DateTime, obj.SysUpdatedDate);


            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                Int32 id = Int32.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id > 0)//Successfull.
                {
                    ////Insert so luong chuyen trong phieu cu ve lai tinh trang ban dau
                    foreach (ChiTietPhieuChuyenKhoResult objOldChiTiet in lstOldData)
                    {
                        MatHangTonKho objTonKho = new MatHangTonKho();
                        objTonKho.MaDonViTinh = objOldChiTiet.MaDonViTinh;
                        objTonKho.MaKho = objOld.MaKhoDen;
                        objTonKho.MaMatHang = objOldChiTiet.MaMatHang;
                        objTonKho.SoLuongTon = objOldChiTiet.SoLuongChuyen;
                        if (!MatHangTonKhoDao.RemoveMatHangTonKho(objTonKho))
                        {
                            ManagerDao.Rollback();
                            return false;
                        }
                        ////
                        MatHangTonKho objTonKhoReset = new MatHangTonKho();
                        objTonKhoReset.MaDonViTinh = objOldChiTiet.MaDonViTinh;
                        objTonKhoReset.MaKho = objOld.MaKhoChuyen;
                        objTonKhoReset.MaMatHang = objOldChiTiet.MaMatHang;
                        objTonKhoReset.SoLuongTon = objOldChiTiet.SoLuongChuyen;
                        if (!MatHangTonKhoDao.Insert(objTonKhoReset))
                        {
                            ManagerDao.Rollback();
                            return false;
                        }
                    }
                    //delete phieu chuyen cu

                    if (!ChiTietPhieuChuyenKhoDao.DeleteByMaPhieuChuyenKho(obj.MaPhieuChuyenKho))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                    //insert lai thong tin phieu moi
                    if (lstChiTiet != null && lstChiTiet.Count > 0)
                    {
                        int TotalSoLuongTon = 0;
                        foreach (ChiTietPhieuChuyenKho objDetail in lstChiTiet)
                        {
                            //get TongSoLuongTon cua mat hang nay
                            TotalSoLuongTon = MatHangDao.GetSoLuongTonByDonViTinh(objDetail.MaMatHang, obj.MaKhoChuyen, objDetail.MaDonViTinh);
                            if (TotalSoLuongTon > 0)
                            {
                                if (objDetail.SoLuongChuyen > TotalSoLuongTon)
                                    objDetail.SoLuongChuyen = TotalSoLuongTon;
                                //insert table chi tiet phieu chuyen
                                objDetail.MaPhieuChuyenKho = obj.MaPhieuChuyenKho;
                                if (!ChiTietPhieuChuyenKhoDao.Insert(objDetail))
                                {
                                    ManagerDao.Rollback();
                                    return false;
                                }
                                //tru bot mat hang ben kho A
                                MatHangTonKho objMatHangTonKhoA = new MatHangTonKho();
                                objMatHangTonKhoA.MaDonViTinh = objDetail.MaDonViTinh;
                                objMatHangTonKhoA.MaKho = obj.MaKhoChuyen;
                                objMatHangTonKhoA.MaMatHang = objDetail.MaMatHang;
                                objMatHangTonKhoA.SoLuongTon = objDetail.SoLuongChuyen;
                                if (!MatHangTonKhoDao.RemoveMatHangTonKho(objMatHangTonKhoA))
                                {
                                    ManagerDao.Rollback();
                                    return false;
                                }
                                //chuyen wa kho B
                                MatHangTonKho objMatHangTonKhoB = new MatHangTonKho();
                                objMatHangTonKhoB.MaDonViTinh = objDetail.MaDonViTinh;
                                objMatHangTonKhoB.MaKho = obj.MaKhoDen;
                                objMatHangTonKhoB.MaMatHang = objDetail.MaMatHang;
                                objMatHangTonKhoB.SoLuongTon = objDetail.SoLuongChuyen;
                                if (!MatHangTonKhoDao.Insert(objMatHangTonKhoB))
                                {
                                    ManagerDao.Rollback();
                                    return false;
                                }
                            }
                        }
                    }
                    ManagerDao.Commit();
                    return true;
                }
                else
                {
                    ManagerDao.Rollback();
                    return false;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            ManagerDao.Rollback();
            return false;
        }
        public static bool Delete(Int64 maPhieu)
        {
            String methodName = "DeletePhieuChuyenKho";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {

                ManagerDao.BeginTransaction();
                List<ChiTietPhieuChuyenKhoResult> lstChiTietOld = ChiTietPhieuChuyenKhoDao.GetByMaPhieuChuyenKho(maPhieu);
                //get MaKho Cu
                PhieuChuyenKho objOldPhieuChuyen = Get(maPhieu);
                if (objOldPhieuChuyen == null)
                {
                    ManagerDao.Rollback();
                    return false;
                }
                try
                {
                    //rollback old data
                    if (lstChiTietOld != null && lstChiTietOld.Count > 0)
                    {
                        foreach (ChiTietPhieuChuyenKhoResult objOldDetail in lstChiTietOld)
                        {

                            //tru bot mat hang ben kho B
                            MatHangTonKho objMatHangTonKhoB = new MatHangTonKho();
                            objMatHangTonKhoB.MaDonViTinh = objOldDetail.MaDonViTinh;
                            objMatHangTonKhoB.MaKho = objOldPhieuChuyen.MaKhoDen;
                            objMatHangTonKhoB.MaMatHang = objOldDetail.MaMatHang;
                            objMatHangTonKhoB.SoLuongTon = objOldDetail.SoLuongChuyen;
                            if (!MatHangTonKhoDao.RemoveMatHangTonKho(objMatHangTonKhoB))
                            {
                                ManagerDao.Rollback();
                                return false;
                            }
                            //chuyen lai kho A
                            MatHangTonKho objMatHangTonKhoA = new MatHangTonKho();
                            objMatHangTonKhoA.MaDonViTinh = objOldDetail.MaDonViTinh;
                            objMatHangTonKhoA.MaKho = objOldPhieuChuyen.MaKhoChuyen;
                            objMatHangTonKhoA.MaMatHang = objOldDetail.MaMatHang;
                            objMatHangTonKhoA.SoLuongTon = objOldDetail.SoLuongChuyen;
                            if (!MatHangTonKhoDao.Insert(objMatHangTonKhoA))
                            {
                                ManagerDao.Rollback();
                                return false;
                            }
                        }
                    }
                    //delete old data
                    if (!ChiTietPhieuChuyenKhoDao.DeleteByMaPhieuChuyenKho(maPhieu))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                    DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spDeletePhieuChuyenKho");
                    //Add value "MaPhieuChuyenKho"  paramater.
                    ManagerDao.AddInParameter(dbCommand, "MaPhieuChuyenKho", DbType.Int64, maPhieu);
                    //Add value returnValue  paramater.
                    ManagerDao.AddParameter(dbCommand, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
                    ManagerDao.ExecuteNonQuery(dbCommand);
                    int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, "returnValue");
                    if (parameterValue == 1)
                    {
                        ManagerDao.Commit();
                        return true;
                    }
                    else
                    {
                        ManagerDao.Rollback();
                        return true;
                    }
                }
                catch (Exception)
                {

                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);

            }
            ManagerDao.Rollback();
            return true;
        }

    }
}
        #endregion